from pymodbus.server import StartTcpServer
from pymodbus.datastore import ModbusSequentialDataBlock
from pymodbus.datastore import ModbusSlaveContext, ModbusServerContext
from pymodbus.exceptions import ModbusException
from threading import Thread
import logging

# 启用调试日志
logging.basicConfig()
log = logging.getLogger()
log.setLevel(logging.ERROR)

def create_modbus_server(port):
    try:
        # 创建数据块
        # DO (Coils) - 10个写入
        do_block = ModbusSequentialDataBlock(0, [0] * 100)
        # DI (Discrete Inputs) - 10个监听
        di_block = ModbusSequentialDataBlock(0, [0] * 100)
        # AI (Input Registers) - 300个写入
        ai_block = ModbusSequentialDataBlock(0, [0] * 300)
        # AO (Holding Registers) - 10个监听
        ao_block = ModbusSequentialDataBlock(0, [0] * 300)

        # 创建从站上下文
        slave_context = ModbusSlaveContext(
            di=di_block,
            co=do_block,
            hr=ao_block,
            ir=ai_block
        )

        # 创建服务器上下文
        server_context = ModbusServerContext(slaves=slave_context, single=True)

        # 启动服务器
        print(f"Starting Modbus TCP server on port {port}")
        StartTcpServer(context=server_context, address=("0.0.0.0", port))
    except ModbusException as e:
        print(f"Modbus exception on port {port}: {e}")

def main():
    threads = []
    for port in range(10502, 10522):
        thread = Thread(target=create_modbus_server, args=(port,))
        threads.append(thread)
        thread.start()

    for thread in threads:
        thread.join()

if __name__ == "__main__":
    main()